<?php

namespace App\Kuafu\Order\Controller\B;

use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Base\Enum\BaseCodeEnum;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Enum\OrderCodeEnum;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\Order\Service\OrderStatisticsService;
use App\Kuafu\Order\Validate\OrderStatisticsValidate;
use App\Kuafu\Shop\Service\ShopService;
use App\Support\ExcelService;
use App\Support\Util;
use Illuminate\Http\Request;
use Illuminate\Validation\Validator;

class OrderController extends BaseController
{
    /**
     * 结账方式列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function payChannels()
    {
        $list = [];
        foreach (CodeEnum::CHANNEL_CODE_TEXT as $id => $name) {
            $list[] = compact('id', 'name');
        }
        return $this->success($list);
    }

    public function index(Request $request)
    {
        $orderId           = (string)$request->orderId;
        $serialNum         = (int)$request->serialNum;
        $completeTimeStart = (string)$request->completeTimeStart; // 格式：2021-09-13
        $completeTimeEnd   = (string)$request->completeTimeEnd;
        $productName       = (string)$request->productName;
        $sourceType        = (int)$request->sourceType;
        $payChannel        = (string)$request->payChannel;
        $sortBy            = (string)$request->sortBy;
        $sort              = (string)$request->sort;
        $brandId           = (int)$request->header('brandId');
        $shopId            = (int)$request->get('shopId');
        $pageNum           = (int)$request->get('pageNum', 1);
        $pageSize          = (int)$request->get('pageSize', 20);
        $orderStatus       = (int)$request->orderStatus;
        if (Util::isDate($completeTimeStart)) {
            $completeTimeStart .= ' 00:00:00';
        }
        if (Util::isDate($completeTimeEnd)) {
            $completeTimeEnd .= ' 23:59:59';
        }

        $this->validate($request, [
            'completeTimeStart' => 'required|date',
            'completeTimeEnd'   => 'required|date',
            'shopId'            => 'required|integer',
        ], [
            'completeTimeStart.required' => "开始日期不能为空",
            'completeTimeEnd.required'   => "结束日期不能为空",
            'shopId.required'            => "门店不能为空",
        ]);

        return $this->success(
            OrderService::bOrderList(
                $brandId,
                $shopId,
                auth('api')->user()->id,
                $completeTimeStart,
                $completeTimeEnd,
                $productName,
                $serialNum,
                $payChannel,
                $sortBy,
                $sort,
                $pageSize,
                $pageNum,
                $sourceType > 0 ? [$sourceType] : [],
                $orderId,
                $orderStatus
            )
        );
    }

    public function shortList(Request $request)
    {
        $completeTimeStartDate = (string)$request->get('completeTimeStartDate'); // 格式：2021-09-13
        $completeTimeEndDate   = (string)$request->get('completeTimeEndDate');
        $shopId            = (int)$request->get('shopId');


//        dd($completeTimeStartDate);

        return $this->success(
            OrderService::bShortList(
                $shopId,
                strtotime($completeTimeStartDate),
                strtotime($completeTimeEndDate)
            )
        );
    }

    /**
     * 订单详情页
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id, Request $request)
    {
        $brandId = (int)$request->header('brandId');
        $shopId  = (int)$request->get('shopId', 0);
        $detail  = OrderService::bOrderDetail($id, $brandId, auth('api')->user()->id, $shopId);
        if (null === $detail) {
            return $this->fail(BaseCodeEnum::NOT_FOUND, '订单不存在');
        }
        return $this->success($detail);
    }

    public function waiMaiOrderList(Request $request)
    {
        $serialNum         = (int)$request->serialNum;
        $completeTimeStart = (string)$request->completeTimeStart; // 格式：2021-09-13
        $completeTimeEnd   = (string)$request->completeTimeEnd;
        $productName       = (string)$request->productName;
        $payChannel        = (string)$request->payChannel;
        $sourceType        = (int)$request->sourceType;
        $sortBy            = (string)$request->sortBy;
        $sort              = (string)$request->sort;
        $brandId           = (int)$request->header('brandId');
        $shopId            = (int)$request->get('shopId');
        $pageNum           = (int)$request->get('pageNum', 1);
        $pageSize          = (int)$request->get('pageSize', 20);
        if (Util::isDate($completeTimeStart)) {
            $completeTimeStart .= ' 00:00:00';
        }
        if (Util::isDate($completeTimeEnd)) {
            $completeTimeEnd .= ' 23:59:59';
        }
        return $this->success(
            OrderService::bOrderList(
                $brandId,
                $shopId,
                auth('api')->user()->id,
                $completeTimeStart,
                $completeTimeEnd,
                $productName,
                $serialNum,
                $payChannel,
                $sortBy,
                $sort,
                $pageSize,
                $pageNum,
                $sourceType > 0 ? [$sourceType] : [],
            )
        );
    }

    /**
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \App\Kuafu\Order\Exceptions\OrderException
     */
    public function bProductSellStatisticsExcel(Request $request)
    {
        $valid = OrderStatisticsValidate::productSaleStatistics($request);
        if ($valid) {
            return $this->fail(OrderCodeEnum::ERR_400000, $valid);
        }

        $shopId  = (int)$request->get('shopId');
        $startAt = (string)$request->get('startAt');
        $endAt   = (string)$request->get('endAt');
        $orderBy = (string)$request->get('orderBy');
        $byType  = (string)$request->get('byType');
        $source  = (int)$request->get('source');

        (new ExcelService)->salesGoodsExcel($shopId, $startAt, $endAt, $orderBy, $byType, $source, true);
    }

    public function bProductSellStatistics(Request $request)
    {
        $valid = OrderStatisticsValidate::productSaleStatistics($request);
        if ($valid) {
            return $this->fail(OrderCodeEnum::ERR_400000, $valid);
        }
        $source     = (int)$request->source ?: 1;
        $shopId     = $request->shopId;
        $startAt    = (int)strtotime($request->startAt);
        $endAt      = (int)strtotime($request->endAt);
        $orderBy    = $request->orderBy ?: 'num';
        $byType     = $request->byType ?: 'desc';
        $service    = new OrderStatisticsService();
        $statistics = $service->bProductSellStatistics($startAt, $endAt, $shopId, $orderBy, $byType, $source);
        return $this->success($statistics);
    }


}
